package com.huang.demo1;

import java.util.Locale;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//基本买票问题
// oop模式 调用对象
public class SaleTickerDemo2 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(()->{
            for (int i = 0; i < 20; i++)
                ticket.buy();


        },"A").start();

    new Thread(()->{
        for (int i = 0; i < 20; i++) {
            ticket.buy();
        }
    },"B").start();

    new Thread(()->{
        for (int i = 0; i < 20; i++) {
            ticket.buy();
        }
        },"C").start();
        }


}

class Ticket2{
    /*
    *  1 加锁
    * 2try执行
    * 3 finally解锁
    * */
    private int number=10;
   Lock lock=new ReentrantLock();

    public  void buy(){
        lock.lock();

        //   尝试获取锁防止一直等待 lock.tryLock();
        try{
            if(number>0){
                System.out.println(Thread.currentThread().getName()+"--"+"卖出了第"+number--+"张票"+"剩余"+number);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

}